/**
 * Project: springyounger.lottery.web
 * 
 * File Created at 2010-3-29
 * $Id$
 * 
 * Copyright 2009 Zjut Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Zjut Edu. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Zjut Edu.
 */
package com.springyouner.lottery.admin;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.util.WebUtils;

import com.springyouner.lottery.framework.UserSession;
import com.springyouner.lottery.tools.LotteryUtil;
import com.springyounger.lottery.dal.dataobject.LotteryPhase;
import com.springyounger.lottery.dal.dataobject.LotteryPhaseQuestion;
import com.springyounger.lottery.dal.dataobject.LotteryQuestionResult;
import com.springyounger.lottery.dal.dataobject.LotteryQuota;
import com.springyounger.lottery.dal.dataobject.User;
import com.springyounger.lottery.service.user.PhaseService;
import com.springyounger.lottery.service.user.QuestionService;

/**
 * TODO Comment of QuestionController
 * 
 * @author springyounger
 */
public class QuestionController extends MultiActionController {
	private static final Logger logger = LoggerFactory
			.getLogger(QuestionController.class);
	private PhaseService phaseService;
	private QuestionService questionService;

	@SuppressWarnings("unchecked")
	public ModelAndView firstAnswer(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String flag = "";
		int avaliableCount;
		int usedCount = 0;
		Map model = new HashMap();

		UserSession userSession = (UserSession) WebUtils.getSessionAttribute(
				request, "userSession");
		User user = userSession.getUser();

		// 首次答题处理
		String questionId = request.getParameter("questionId");
		String resultId = request.getParameter("resultId");
		String qid = request.getParameter("phaseId");

		// 获取答案
		LotteryQuestionResult questionResult = questionService
				.getQuestionResult(Integer.parseInt(resultId));
		LotteryPhaseQuestion question = questionService.getPhaseQuestion(
				Integer.parseInt(questionId), Integer.parseInt(qid));

		LotteryPhase lotteryPhase = phaseService.getPhaseById(question
				.getPhaseId());

		if (null == questionResult || null == question || null == lotteryPhase) {
			logger.info("题目和答案异常");
			return new ModelAndView("user/lotteryError", model);
		}
		model.put("phaseId", String.valueOf(question.getPhaseId()));

		avaliableCount = lotteryPhase.getDailyQuestion();
		if (avaliableCount <= 0) {
			// 配额已经用完
			flag = "quotaZero";
			model.put("flag", flag);
			return new ModelAndView("user/lotteryError", model);
		}

		avaliableCount--;
		// 答题配额
		LotteryQuota lotteryQuota = new LotteryQuota();
		lotteryQuota.setPhaseId(lotteryPhase.getPhaseId());
		lotteryQuota.setUserId(user.getUserid());
		lotteryQuota.setQuotaAmount(lotteryPhase.getDailyQuestion());
		// 配额减一
		lotteryQuota.setAvaliableCount(avaliableCount);
		lotteryQuota.setQuotaDate(LotteryUtil.getToday());
		lotteryQuota.setQuotaType(LotteryQuota.LOTTERY_DAILY);

		// 关数加一

		usedCount++;
		// 获取答题配额对象
		LotteryQuota quota = phaseService.getLotteryQuota(lotteryQuota);

		if (null != quota) {
			// 重复答题
			flag = "reAnswer";
			model.put("flag", flag);
			return new ModelAndView("user/lotteryError", model);
		}

		// 创建答题配额
		boolean success = phaseService.insertLotteryQuota(lotteryQuota);
		if (!success) {
			// 创建失败
			flag = "systemError";
			model.put("flag", flag);
			return new ModelAndView("user/lotteryError", model);
		}

		// 答题是否正确
		if (!"y".equalsIgnoreCase(questionResult.getIsSolution())) {
			// 回答错误
			model.put("avaliableCount", String.valueOf(avaliableCount));
			model.put("usedCount", String.valueOf(usedCount));
			return new ModelAndView("user/answerResult", model);
		}

		model.put("avaliableCount", String.valueOf(avaliableCount));
		model.put("usedCount", String.valueOf(usedCount));
		return new ModelAndView("user/initLottery", model);
	}

	@SuppressWarnings("unchecked")
	public ModelAndView nextAnswer(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 下一次答题
		String flag = "";
		int avaliableCount;
		int usedCount;
		Map model = new HashMap();
		UserSession userSession = (UserSession) WebUtils.getSessionAttribute(
				request, "userSession");
		User user = userSession.getUser();

		String questionId = request.getParameter("questionId");
		String resultId = request.getParameter("resultId");
		String qid = request.getParameter("phaseId");

		// 获取答案
		LotteryQuestionResult questionResult = questionService
				.getQuestionResult(Integer.parseInt(resultId));
		LotteryPhaseQuestion question = questionService.getPhaseQuestion(
				Integer.parseInt(questionId), Integer.parseInt(qid));

		if (null == questionResult || null == question) {
			logger.info("题目和答案异常");
			return new ModelAndView("user/lotteryError", model);
		}

		model.put("phaseId", String.valueOf(question.getPhaseId()));

		LotteryQuota lotteryQuota = new LotteryQuota();
		lotteryQuota.setPhaseId(question.getPhaseId());
		lotteryQuota.setUserId(user.getUserid());
		lotteryQuota.setQuotaType(LotteryQuota.LOTTERY_DAILY);
		lotteryQuota.setQuotaDate(LotteryUtil.getToday());

		LotteryQuota quota = phaseService.getLotteryQuota(lotteryQuota);
		// 可用配额
		avaliableCount = quota.getAvaliableCount();
		// 已经使用的配额
		usedCount = quota.getQuotaAmount() - avaliableCount;
		// 下一题序号
		String publishSn = String.valueOf(usedCount + 1);

		if (avaliableCount > 0) {
			usedCount++;
			avaliableCount--;
		}

		// 题目已经答过
		if (!publishSn.equals(question.getPublishSn())) {
			flag = "reAnswer";
			avaliableCount = quota.getAvaliableCount();
			usedCount = quota.getQuotaAmount() - avaliableCount;
			model.put("flag", flag);
			model.put("avaliableCount", String.valueOf(avaliableCount));
			model.put("usedCount", String.valueOf(usedCount));
			return new ModelAndView("user/lotteryError", model);
		}

		// 更新配额
		quota.setAvaliableCount(avaliableCount);

		boolean success = phaseService.updateLotteryQuota(quota);
		if (!success) {
			// 更新失败
			flag = "systemError";
			model.put("flag", flag);
			return new ModelAndView("user/lotteryError", model);
		}

		// 答题是否正确
		if (!"y".equalsIgnoreCase(questionResult.getIsSolution())) {
			// 回答错误
			model.put("avaliableCount", String.valueOf(avaliableCount));
			model.put("usedCount", String.valueOf(usedCount));
			return new ModelAndView("user/answerResult", model);
		}

		model.put("avaliableCount", String.valueOf(avaliableCount));
		model.put("usedCount", String.valueOf(usedCount));
		return new ModelAndView("user/initLottery", model);
	}

	/**
	 * @param phaseService
	 *            the phaseService to set
	 */
	public void setPhaseService(PhaseService phaseService) {
		this.phaseService = phaseService;
	}

	/**
	 * @param questionService
	 *            the questionService to set
	 */
	public void setQuestionService(QuestionService questionService) {
		this.questionService = questionService;
	}

}
